import logging
from django.utils import timezone

from django.db.models import Q
from django.shortcuts import render
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from rest_framework.permissions import IsAuthenticated

from courses.models import Course, CourseExpire, CourseChapter
from courses.serializers import CourseSerializer, CourseDetailSerializer, CourseChapterSerializer
from orders.models import OrderDetail

logger = logging.getLogger('django')


# Create your views here.
class CoursePage(PageNumberPagination):
    # 默认每页显示数量
    page_size = 10

    # 每页最大数量的参数名
    page_size_query_param = 'page_size'

    # 每页最大数量限制
    max_page_size = 50

    def get_paginated_response(self, data):
        return Response({
            "code": 1,
            "message": "SUCCESS",
            "data": {
                'count': self.page.paginator.count,  # 总数量
                'next': self.get_next_link(),  # 下一页的连接
                'previous': self.get_previous_link(),  # 上一页的连接
                'results': data  # 当前页的数据
            }

        })


class CourseListView(ListAPIView):
    """
    http://127.0.0.1:8000/api/courses/?nav_name=免费课
    """
    serializer_class = CourseSerializer
    pagination_class = CoursePage

    def get_queryset(self):
        """
        重写查询方法
        :return: 根据导航名称筛选后的课程查询集
        """

        # 获取查询参数重的导航名称
        nav_name = self.request.query_params.get("nav_name", "")
        category_id = self.request.query_params.get("categoryId", "")
        sort_ord = self.request.query_params.get("sortord", "")
        price_range = self.request.query_params.get("price_range", "")
        keywords = self.request.query_params.get("keywords", "").strip()  # 去除前后空格

        logger.info(f"正在查询导航分类[{nav_name}],课程分类[{category_id}],排序方式[{sort_ord}]下的课程信息")
        #
        # if not nav_name:
        #     logger.info("未提供导航名称参数,返回空数据")
        #     return Course.objects.none()

        try:

            # 构建基础数据
            query_set = Course.objects.filter(status=1)

            # 根据导航名称过滤
            if nav_name:
                logger.info(f"正在g根据导航分类[{nav_name}.过滤")
                query_set = query_set.filter(nav_relations__nav_category__name=nav_name)

            # 根据分类ID过滤
            if category_id and category_id != '0':
                logger.info(f"正在根据课程分类:[{category_id}]过滤")
                query_set = query_set.filter(categories__id=category_id)

            if price_range:
                if price_range == '1':  # 免费
                    query_set = query_set.filter(course_type=1)
                elif price_range == '2':  # 付费
                    query_set = query_set.filter(course_type=2)

            if keywords:
                logger.info(f"正在根据关键字[{keywords}]过滤")
                query_set = query_set.filter(Q(name__icontains=keywords) | Q(teacher__name__icontains=keywords))

                # 如果没有任何的过滤条件
            if not nav_name and not category_id and not price_range and not keywords:
                logger.info("未提供任何过滤条件,返回空数据")
                return Course.objects.none()

            order_field = '-created_time'  # 默认排序方式
            if sort_ord:
                if sort_ord == '1':
                    order_field = "-pub_date"  # 最新
                    logger.info("正在根据最新排序方式排序")
                if sort_ord == '2':
                    order_field = "-students"  # 最热
                    logger.info("正在根据最热排序方式排序")

                if sort_ord == '3':
                    order_field = "price"  # 价格
                    logger.info("正在根据价格排序方式排序")

            # 优化查询
            query_set = query_set.select_related('teacher').order_by(order_field).distinct()

            course_count = query_set.count()
            logger.info(f"查询到导航分类{nav_name}下的课程数量:{course_count}")

            return query_set

        except Exception as e:
            logger.error(f"查询课程列表发生异常:{str(e)}")
            return Course.objects.none()


class CourseDeatailAPIView(RetrieveAPIView):
    queryset = Course.objects.filter(is_deleted=False, status=1)
    serializer_class = CourseDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        try:
            instance = self.get_object()
            serializer = self.get_serializer(instance)

            logger.info(f"正在获取课程详情,id:{instance.id}")
            return Response({
                "code": 1,
                "message": "SUCCESS",
                "data": serializer.data
            })
        except Exception as e:
            logger.error(f"获取课程详情发生异常:{str(e)}")
            return Response({
                "code": 0,
                "message": f"获取课程详情失败:{str(e)}"
            })


class CourseExpireAPIView(APIView):

    def get(self, request, *args, **kwargs):
        """
        请求参数:
            1:?course_ids=1,2,3,4  ?course_ids=1
        返回值:包括课程ID---》价格 ,有效期
        """
        try:

            # 从请求获取参数 1,2,3==>[1,2,3]
            course_ids = request.query_params.get("course_ids")
            logger.info(f"正在获取课程:{course_ids}的课程有效期信息")
            if not course_ids:
                return Response({
                    "code": 0,
                    "message": "参数错误:请提供课程ID"
                })
            course_id_list = [int(id) for id in course_ids.split(",")]
            logger.info(f"正在获取课程:{course_id_list}的课程有效期信息")

            # [1,2,3]
            if not course_id_list:
                return Response({
                    "code": 0,
                    "message": "格式错误"
                })

            coures = Course.objects.filter(
                id__in=course_id_list,
                is_deleted=False,
                status=1
            ).values("id", "name", "price")
            logger.info(f"查询到课程:{coures}")

            course_dict = {str(course['id']): course for course in coures}
            logger.info(f"课程:{course_dict}")

            expire_list = CourseExpire.objects.filter(
                course_id__in=course_id_list
            )
            logger.info(f"查询到课程有效期:{expire_list}")

            # 初始化最终数据的字典
            course_data = {}
            # [1,2,3]
            for expire in expire_list:
                course_id = str(expire.course_id)
                logger.info(f"正在处理课程:{course_id}")
                logger.info(course_data)

                # 如果这个课程还没有出现到course_data结果字典中, 初始化最外层的数据结构
                if course_id not in course_data:
                    course_data[course_id] = {
                        'name': expire.course.name,
                        "expire_list": []
                    }

                course_data[course_id]['expire_list'].append(
                    {
                        'expire_time': expire.expire_time,
                        'expire_text': f"{expire.expire_time}天" if expire.expire_time > 0 else "永久有效",
                        "price": float(expire.price)
                    }
                )
                logger.info(course_data)

            for course_id, course_info in course_dict.items():
                logger.info(course_id)
                logger.info(course_info)

                if course_id not in course_data:
                    logger.info(f"加默认值:{course_id}")
                    course_data[course_id] = {
                        'name': course_info['name'],
                        'expire_list': [
                            {
                                'expire_time': 0,
                                'expire_text': "永久有效",
                                'price': float(course_info['price'])
                            }

                        ]
                    }

            # 返回结果
            return Response({
                "code": 1,
                "message": "SUCCESS",
                "data": course_data
            })


        except Exception as e:
            logger.error(f"获取课程有效期信息发生异常:{str(e)}")
            return Response({
                "code": 0,
                "message": f"获取课程有效期信息失败:{str(e)}"
            })


class CourseContentAPIView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):

        course_id = request.query_params.get("course_id")
        order_number = request.query_params.get("order_number")

        if not all([order_number, course_id]):
            return Response({"code": 0, "message": "参数错误"})
        try:

            # select_related:用于 一对一 或者多对一关系
            order_detail = OrderDetail.objects.select_related('order').get(
                order_number=order_number,
                course_id=course_id,
                order__user=request.user  # 夸表查询,确保当前订单是这个 用户
            )

            if order_detail.order.order_status != 1:
                return Response({"code": 0, "message": "订单未支付"})

            if order_detail.expire_time and order_detail.expire_time < timezone.now():
                return Response({"code": 0, "message": "课程已过期"})

            # 获取课程章节和课时信息

            # prefetch_related: 用于 一对多关系 或者 多对多关系
            chapters = CourseChapter.objects.filter(
                course_id=course_id
            ).prefetch_related("lessons").order_by("number")

            logger.info(chapters)

            ser = CourseChapterSerializer(chapters, many=True)

            return Response({"code": 1, "message": "SUCCESS", "data": ser.data})

        except Exception as e:
            logger.error(f"获取课程内容发生异常:{str(e)}")
            return Response({"code": 0, "message": f"获取课程内容失败:{str(e)}"})
